package de.bazinga.rotw.util;

import java.net.InetAddress;
import java.net.UnknownHostException;

/*
 * Singleton 
 */
public class NetworkConstants
{
	private static NetworkConstants instance = new NetworkConstants();
	
	public static final int SERVER_TCP_PORT = 8011;
	public static final int SERVER_UDP_PORT = 8011;
	public static final int UPDATE_INTERVALL = 20;
	public static final int LAN_SEARCH_TIMEOUT = 500;
	

	public static final long OBJ_PLAYER = 0;
	public static final long OBJ_BULLET = 1;
	public static final long OBJ_PORTAL_ENTRY = 2;
	public static final long OBJ_PORTAL_EXIT = 3;
	
	private InetAddress remoteServerAddress;
	private String localIP;

	
	private NetworkConstants()
	{
		try
		{
			localIP = getLocalIPAddress();
			remoteServerAddress = InetAddress.getByName(localIP); //initially localhost
		}
		catch (UnknownHostException e)
		{			
			e.printStackTrace();
		}
	}
	
	public static NetworkConstants getInstance()
	{
		return instance;
	}
	
	private String getLocalIPAddress()
	{
		InetAddress[] allLocalIPs = null;
		try
		{
			allLocalIPs = InetAddress.getAllByName(InetAddress.getLocalHost().getHostName());
		}
		catch (UnknownHostException e)
		{
			e.printStackTrace();
			return null;
		}
		
		String localIPLiteral = null;
		for(InetAddress localIP: allLocalIPs)
		{
			localIPLiteral = localIP.getHostAddress();
			String startToken = localIPLiteral.substring(0,localIPLiteral.indexOf(".")); 
			if(!startToken.equals("127") && !startToken.equals("0"))
			{
				break;
			}
		}
		return localIPLiteral;
	}

	public String getLocalIP()
	{
		return localIP;
	}

	/**
	 * Sets the NetworkConstant localIP.
	 * 
	 * @param localIP
	 */
	public void setLocalIP(String localIP)
	{
		this.localIP=localIP;		
	}
	
	/**
	 * Sets the NetworkConstant remoteServerAddress.
	 * This method is usefull if a client wants to connect directly
	 * to a known server.
	 * @param serverIP
	 */
	public void setRemoteServerAddress(String serverIP)
	{
		try
		{
			this.remoteServerAddress = InetAddress.getByName(serverIP);
		}
		catch (UnknownHostException e)
		{
			e.printStackTrace();
		}
	}

	public InetAddress getRemoteServerAddress()
	{
		return remoteServerAddress;
	}

	public void setRemoteServerAddress(InetAddress remoteServerAddress)
	{
		this.remoteServerAddress=remoteServerAddress;
	}
	
	
}
